<template>
  <div class='category'>
    <!-- 输入框 -->
    <el-row :gutter="20">
      <el-col :span="4">
        <el-input v-model="SearchCategoryVo.categoryName" placeholder="请输入分类名称"></el-input>
      </el-col>
      <el-col :span="4">
        <el-select v-model="SearchCategoryVo.type" placeholder="请选择分类类型">
          <el-option v-for="item in categoryType" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="4" style="text-align: left">
        <el-button type="primary" @click="searchCategoryByConditions(true)" icon="el-icon-search">查询</el-button>
      </el-col>
      <el-col :span="12" style="text-align: right">
        <el-button type="primary" @click="addCategoryVisible = true" icon="el-icon-plus">添加分类</el-button>
      </el-col>
    </el-row>
    <!-- 表格 -->
    <el-table :data="categoryList" stripe style="width: 100%" height="550" v-loading="loading">
      <el-table-column type="index" width="50" align="center" label="序号">
      </el-table-column>
      <el-table-column prop="categoryName" label="分类名称" width="120" align="center">
      </el-table-column>
      <el-table-column prop="type" label="分类类型" width="120" align="center">
      </el-table-column>
      <el-table-column prop="sort" label="排序" width="120" align="center">
      </el-table-column>
      <el-table-column prop="createUser" label="创建人" width="120" align="center">
      </el-table-column>
      <el-table-column prop="createDate" label="创建时间" width="200" align="center">
      </el-table-column>
      <el-table-column prop="updateUser" label="修改人" width="120" align="center">
      </el-table-column>
      <el-table-column prop="updateDate" label="修改时间" width="200" align="center">
      </el-table-column>
      <el-table-column label="操作" width="156" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button @click="checkCategory(scope.row.id)" type="text" size="mini" style="color: #67c23a;"><i class="el-icon-view"></i>查看</el-button>
          <el-button type="text" @click="getCategoryById(scope.row.id)" size="mini"><i class="el-icon-edit"></i>编辑</el-button>
          <el-button type="text" @click="delCategory(scope.row.id)" size="mini" style="color: #f56c6c;"><i class="el-icon-delete"></i>删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页条 -->
    <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :page-sizes="[15, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper" :total="dataSize"
      align="center">
    </el-pagination>
    <!-- 添加分类 -->
    <el-dialog title="添加分类" :visible.sync="addCategoryVisible" width="35%" :before-close="cancelAddCategory">
      <el-form ref="form" :model="CategoryBasic" :rules="AddCategoryRules" label-width="100px" label-position="left" style="margin: 20px 40px;">
        <el-form-item label="分类名称:" prop="categoryName">
          <el-input v-model="CategoryBasic.categoryName" style="width: 280px;" placeholder="请输入分类名称"></el-input>
        </el-form-item>
        <el-form-item label="排序:">
          <el-input v-model="CategoryBasic.sort" style="width: 280px;" placeholder="请输入排序"></el-input>
        </el-form-item>
        <el-form-item label="分类类型:" prop="type">
          <el-select v-model="CategoryBasic.type" placeholder="请选择分类类型" style="width: 280px;">
            <el-option v-for="item in categoryType" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述:">
          <el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="CategoryBasic.description" style="width: 280px;">
          </el-input>
        </el-form-item>
        <div style="margin-top: 40px"></div>
        <el-form-item>
          <el-button type="primary" @click="AddCategory">保存</el-button>
          <el-button style="margin-left: 80px;" @click="cancelAddCategory">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 查看分类信息 -->
    <el-dialog title="分类信息" :visible.sync="checkCategoryVisible" :before-close="cancelCheckCategory">
      <el-descriptions column="1" border>
        <el-descriptions-item label="分类名称">{{ CategoryBasicDto.categoryName}}</el-descriptions-item>
        <el-descriptions-item label="分类类型">{{ changeType(CategoryBasicDto.type) }}</el-descriptions-item>
        <el-descriptions-item label="排序">{{ CategoryBasicDto.sort }}</el-descriptions-item>
        <el-descriptions-item label="创建人">{{ CategoryBasicDto.createUser }}</el-descriptions-item>
        <el-descriptions-item label="修改人">{{ CategoryBasicDto.updateUser }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ CategoryBasicDto.createDate }}</el-descriptions-item>
        <el-descriptions-item label="修改时间">{{ CategoryBasicDto.updateDate }}</el-descriptions-item>
        <el-descriptions-item label="描述">{{ CategoryBasicDto.description }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
    <!-- 编辑分类信息 -->
    <el-dialog title="编辑分类" :visible.sync="editCategoryVisible" width="35%" :before-close="cancelEditCategory">
      <el-form ref="form" :model="CategoryBasic" :rules="AddCategoryRules" label-width="100px" label-position="left" style="margin: 20px 40px;">
        <el-form-item label="分类名称:" prop="categoryName">
          <el-input v-model="CategoryBasic.categoryName" style="width: 280px;" placeholder="请输入分类名称"></el-input>
        </el-form-item>
        <el-form-item label="排序:">
          <el-input v-model="CategoryBasic.sort" style="width: 280px;" placeholder="请输入排序"></el-input>
        </el-form-item>
        <el-form-item label="描述:">
          <el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="CategoryBasic.description" style="width: 280px;">
          </el-input>
        </el-form-item>
        <div style="margin-top: 40px"></div>
        <el-form-item>
          <el-button type="primary" @click="editCategory">保存</el-button>
          <el-button style="margin-left: 80px;" @click="cancelEditCategory">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import request from '@/utils/request'

export default {
  name: 'CategoryIndex',
  // import引入的组件需要注入到对象中才能使用
  components: {},
  data () {
    // 这里存放数据
    return {
      loading: true,
      baseCategory: '/category-basic',
      pageIndex: 1,
      pageSize: 15,
      dataSize: 0,
      // 添加分类表单显示状态
      addCategoryVisible: false,
      // 查看分类详细信息显示状态
      checkCategoryVisible: false,
      // 编辑分类表单显示状态
      editCategoryVisible: false,
      // 分类类型
      categoryType: [
        {
          value: 1,
          label: '菜品'
        },
        {
          value: 2,
          label: '套餐'
        }
      ],
      CategoryBasicDto: {
        id: 0,
        categoryName: '',
        sort: 0,
        type: '',
        description: '',
        createUser: '',
        createDate: new Date(),
        updateUser: '',
        updateDate: new Date(),
        isDeleted: false
      },
      CategoryBasic: {
        id: 0,
        categoryName: '',
        sort: 0,
        type: '',
        description: '',
        createUser: 0,
        // createDate: new Date(),
        updateUser: 0,
        // updateDate: new Date(),
        isDeleted: false
      },
      // 查询分类参数对象
      SearchCategoryVo: {
        categoryName: '',
        type: ''
      },
      categoryList: [],
      AddCategoryRules: {
        categoryName: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3到 5 个字符', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择分类类型', trigger: 'change' }
        ]
      }
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {
    categoryList: {
      deep: true,
      immediate: true,
      handler (newCategoryList) {
        newCategoryList = newCategoryList.forEach(item => {
          item.type = this.changeType(item.type)
          return item
        })
      }
    }
  },
  // 方法集合
  methods: {
    // 根据条件查询分类列表
    searchCategoryByConditions (flag) {
      this.SearchCategoryVo.type = this.SearchCategoryVo.type === '' ? 0 : this.SearchCategoryVo.type
      // 执行查询操作
      request({
        url: this.baseCategory + `/category-list/${this.pageIndex}/${this.pageSize}`,
        method: 'get',
        params: this.SearchCategoryVo
      }).then(result => {
        if (result.data.data.data != null) {
          // 查询成功执行操作
          this.categoryList = result.data.data.data
          this.dataSize = result.data.data.size
          this.loading = false
          if (flag) {
            this.$message({
              message: '查询成功',
              type: 'success'
            })
          }
          // 清除默认数据
          this.SearchCategoryVo = {}
        } else {
          this.$message({
            message: '查询失败',
            type: 'error'
          })
        }
      }).catch(error => {
        this.$message({
          message: '查询失败',
          type: 'error'
        })
        console.log(error)
      })
    },
    // 添加分类
    AddCategory () {
      // 执行添加操作
      request({
        url: this.baseCategory + '/category-basic',
        method: 'post',
        data: this.CategoryBasic
      }).then(result => {
        if (result.data.data) {
          // 添加成功后执行操作
          this.addCategoryVisible = false
          // 保存成功后弹出提示消息
          this.$message({
            message: '添加成功',
            type: 'success'
          })
          // 添加成功后清空默认数据
          this.CategoryBasic = {}
          // 添加成功后刷新界面
          this.searchCategoryByConditions()
        } else {
          // 添加失败后执行操作
          this.$message({
            message: '添加失败',
            type: 'error'
          })
        }
      }).catch(error => {
        console.log(error)
        this.$message({
          message: '添加失败',
          type: 'error'
        })
      })
    },
    // 取消添加分类
    cancelAddCategory () {
      this.addCategoryVisible = false
      // this.$message({
      //   message: '取消成功',
      //   type: 'info'
      // })
    },
    // 查看分类信息
    checkCategory (id) {
      this.checkCategoryVisible = true
      // 根据id查看用户操作
      request({
        url: this.baseCategory + `/category-basic/${id}`,
        method: 'get'
      }).then(result => {
        if (result.data.data != null) {
          // 根据id查看用户操作成功
          this.CategoryBasicDto = result.data.data
          // 根据id查看用户操作成功后弹出提示消息
          // this.$message({
          //   message: '查看分类成功',
          //   type: 'success'
          // })
        } else {
          // 根据id查看用户操作失败
          this.$message({
            message: '查看分类失败',
            type: 'error'
          })
        }
      }).catch(error => {
        console.log(error)
        this.$message({
          message: '查看分类失败',
          type: 'error'
        })
      })
    },
    // 取消查看分类信息
    cancelCheckCategory () {
      this.checkCategoryVisible = false
      // this.$message({
      //   message: '取消成功',
      //   type: 'info'
      // })
    },
    /**
         * 编辑分类
         */
    // 1.回显分类信息
    getCategoryById (id) {
      this.editCategoryVisible = true
      // 根据id查看用户操作
      request({
        url: this.baseCategory + `/category-basic/${id}`,
        method: 'get'
      }).then(result => {
        if (result.data.data != null) {
          // 根据id查看用户操作成功
          const { id, categoryName, sort, description, type } = result.data.data
          this.CategoryBasic = { id, categoryName, sort, description, type }
          // 根据id查看用户操作成功后弹出提示消息
          // this.$message({
          //   message: '回显分类成功',
          //   type: 'success'
          // })
        } else {
          // 根据id查看用户操作失败
          this.$message({
            message: '回显分类失败',
            type: 'error'
          })
        }
      }).catch(error => {
        console.log(error)
        this.$message({
          message: '回显分类失败',
          type: 'error'
        })
      })
    },
    // 2.修改分类
    editCategory () {
      // 执行修改分类操作
      request({
        url: this.baseCategory + '/category-basic',
        method: 'put',
        data: this.CategoryBasic
      }).then(result => {
        if (result.data.data) {
          // 修改分类操作成功
          this.editCategoryVisible = false
          // 修改成功后弹出提示消息
          this.$message({
            message: '编辑成功',
            type: 'success'
          })
          // 修改成功后清空默认数据
          this.CategoryBasic = {}
          // 修改成功后刷新界面
          this.searchCategoryByConditions()
        } else {
          // 修改分类操作失败
          this.$message({
            message: '编辑失败',
            type: 'error'
          })
        }
      }).catch(error => {
        console.log(error)
        this.$message({
          message: '编辑失败',
          type: 'error'
        })
      })
    },
    // 取消修改分类
    cancelEditCategory () {
      this.editCategoryVisible = false
      // 取消修改后清空默认数据
      this.CategoryBasic = {}
      // this.$message({
      //   message: '取消成功',
      //   type: 'info'
      // })
    },
    // 删除分类
    delCategory (id) {
      this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 执行删除操作
        request({
          url: this.baseCategory + `/category-basic/${id}`,
          method: 'delete'
        }).then(result => {
          if (result.data.data) {
            // 删除成功后执行操作
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            // 删除成功后刷新界面
            this.searchCategoryByConditions()
          } else {
            // 删除失败后执行操作
            this.$message({
              type: 'error',
              message: '删除失败!'
            })
          }
        }).catch(error => {
          console.log(error)
          this.$message({
            type: 'error',
            message: '删除失败!'
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 查看分类时根据type的值动态修改为对应字符串
    changeType (type) {
      this.categoryType.forEach(item => {
        if (item.value === type) type = item.label
      })
      return type
    },
    handleSizeChange (val) {
      this.pageSize = val
      this.loading = true
      this.searchCategoryByConditions()
    },
    handleCurrentChange (val) {
      this.pageIndex = val
      this.loading = true
      this.searchCategoryByConditions()
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created () {
    this.searchCategoryByConditions()
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {

  },
  beforeCreate () { }, // 生命周期 - 创建之前
  beforeMount () { }, // 生命周期 - 挂载之前
  beforeUpdate () { }, // 生命周期 - 更新之前
  updated () { }, // 生命周期 - 更新之后
  beforeDestroy () { }, // 生命周期 - 销毁之前
  destroyed () { }, // 生命周期 - 销毁完成
  activated () { } // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style scoped>
.category {
    background-color: #fff;
    height: 690px;
    padding: 20px 20px;
    border-radius: 30px;
}

.el-table {
    margin-top: 20px;
}

.el-pagination {
    margin-top: 20px;
}
</style>
